import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { utilities, WinstonModule, WinstonModuleOptions } from 'nest-winston';
import * as winston from 'winston';
import { Console } from 'winston/lib/winston/transports';
import * as DailyRotateFile from 'winston-daily-rotate-file'
import { LogEnum } from 'src/enum/config.enum';

function createDailyRotateFileTransport(level: string, filename: string) {
    return new DailyRotateFile({
        level,
        dirname: 'logs',
        filename: `${filename}-%DATE%.log`,
        datePattern: 'YYYY-MM-DD-HH',
        zippedArchive: true,
        maxSize: '20m',
        maxFiles: '14d',
        format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.simple()
        )
    });
}

@Module({
    imports: [
        WinstonModule.forRootAsync({
            inject: [ConfigService],
            useFactory: (configService: ConfigService) => {

                const consoleTransport = new Console({
                    level: 'info',
                    format: winston.format.combine(
                        winston.format.timestamp(),
                        utilities.format.nestLike()
                    )
                })

                const transports = configService.get(LogEnum.LOG_ON) === 'true' ? [
                        createDailyRotateFileTransport('info', 'app'),
                        createDailyRotateFileTransport('warn', 'error')
                    ] : []

                return {
                    transports: [
                        consoleTransport,
                        ...transports
                    ]
                } as WinstonModuleOptions
            }
        })
    ],
})
export class LogsModule {}
